package com.nuanshui.heatedloan.fund.biz.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.nuanshui.framework.consts.TransactionManagerType;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.baseservice.facade.OrderNumGenerate;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.heatedloan.constant.AccountBillBizType;
import com.nuanshui.heatedloan.constant.FreezeFundActionType;
import com.nuanshui.heatedloan.constant.FreezeFundState;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.dal.IdTypeHandler;
import com.nuanshui.heatedloan.fund.biz.dal.mapper.UserAccountBillMapper;
import com.nuanshui.heatedloan.fund.biz.dal.mapper.UserFreezeFundActionMapper;
import com.nuanshui.heatedloan.fund.biz.dal.mapper.UserFundActionMapper;
import com.nuanshui.heatedloan.fund.enums.PlatformEnum;
import com.nuanshui.heatedloan.fund.facade.UserFreezeFundActionService;
import com.nuanshui.heatedloan.fund.model.UserAccountBill;
import com.nuanshui.heatedloan.fund.model.UserFreezeFundAction;
import com.nuanshui.heatedloan.fund.model.UserFundAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;


@Service
@Transactional(readOnly=true,value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
public class UserFreezeFundActionServiceImpl extends CommonServiceImpl implements UserFreezeFundActionService {

	@Autowired
	private  UserFreezeFundActionMapper userFreezeFundActionMapper;
	
	
	@Autowired
	private UserFundActionMapper userFundActionMapper;
	
	@Autowired
	private UserAccountBillMapper userAccountBillMapper;

	@Reference(url = GlobalParam.BASESERVICE_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.BASESERVICE_DUBBO_SERVER_VERSION)
	private OrderNumGenerate orderNumGenerate;
	
	
	public static final String NAME = "保证金";
	
	private static final Logger  logger = LoggerFactory.getLogger("user_freeze_fund");

	@Override
	@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public void saveUserFreezeFundAction(
			UserFreezeFundAction userFreezeFundAction) {
		LogUtil.info(logger, "正在执行保证金的相关操作。。。。。。");
		userFreezeFundActionMapper.saveUserFreezeFundAction(userFreezeFundAction);
	}

	@Override
	public Long getUserFreezeFund(String userId) {
		LogUtil.info(logger, "正在查询用户缴纳的保证金数额。。。。。。");
		return userFreezeFundActionMapper.getUserFreezeFund(userId);
	}

	@Override
	public Long getUserAllFreezeFund(String userId) {
		LogUtil.info(logger, "正在查询用户缴纳的保证金数额。。。。。。");
		return userFreezeFundActionMapper.getUserAllFreezeFund(userId);
	}
	
	@Override
	public Long getUserFreezeFundStatus(String userId) {
		LogUtil.info(logger, "正在查询解冻审核中的保证金。。。。。。");
		return userFreezeFundActionMapper.getUserFreezeFundStatus(userId);
	}

	@Override
	@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public void checkUserFreezeFundAction(String freezeId, Integer isPass,
			String billId) {
		LogUtil.info(logger, "用户为管理员，正在执行审核是否通过...");
		if(billId == null) {
			billId = IdTypeHandler.encode(userFreezeFundActionMapper.getBizIdByFreezeId(freezeId));
		}
		if(freezeId == null) {
			freezeId = IdTypeHandler.encode(userFreezeFundActionMapper.getFreezeIdByBizId(billId));
		}		
		Integer isValidated = userFreezeFundActionMapper.validateUserCanbeUnFroozen(freezeId);
		if(isValidated == 0) {
			LogUtil.error(logger, "不允许解冻保证金");
			return;
		}
		
		Integer status = 1; // 初始状态
		if(isPass == 1) {
			status = 10; // 审核通过的状态
		}else if(isPass == 0) {
			status = -1; // 审核不通过的状态
		}else {
			LogUtil.error(logger, "isPass非0,1的其他数字");
		}
		
		userFreezeFundActionMapper.updateFreeFundActionStatus(freezeId, status);
		
		Integer status_bill = 1; //初始状态
		if(isPass == 1) {
			status_bill = 10; // 审核通过的状态
		}else if(isPass == 0) {
			status_bill = -1; // 审核不通过的状态
		}else {
			LogUtil.error(logger, "isPass非0,1的其他数字");
		}
		userAccountBillMapper.updateUserAccountBillStatus(billId, status_bill);
		
		UserFreezeFundAction uffa = userFreezeFundActionMapper.getFreezeFundById(freezeId);

		if(status_bill == 10) {
			LogUtil.info(logger, "审核已通过，正在增加余额...");
			UserFundAction ufa = new UserFundAction();
			
			ufa.setMoney(Long.parseLong(uffa.getMoney()+"") * (-1));
			ufa.setUserId(uffa.getUserId());
			//ufa.setActionType(3);
			ufa.setStatus(10);
			ufa.setPlatform(uffa.getPlatform());
			userFundActionMapper.saveUserFundAction(ufa); // 余额表增加一条“+money”的数据
			LogUtil.info(logger, "余额已添加");		
		}else if(status_bill == -1) {//审核 不通过，商品和店铺上架
			//TODO 
		}
	}
	
	
	@Override
	@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public String payFreezeFund(Long money,String currentUserId) {
		String orderNum = orderNumGenerate.getDealNum(AccountBillBizType.MARGIN);
		LogUtil.info(logger, "缴纳保证金"+money/100+"元");
		UserAccountBill userAccountBill = new UserAccountBill();
		userAccountBill.setUserId(currentUserId);
		userAccountBill.setDealNum(orderNum);
		userAccountBill.setMoney(money*-1);
		userAccountBill.setName(NAME);
		userAccountBill.setStatus(FreezeFundState.CREATE);
		//userAccountBill.setType(AccountBillType.MARGIN);
		userAccountBill.setPlatform("WX");
		userAccountBill.setSubType(FreezeFundActionType.PAY_BOND_MONEY);
		userAccountBillMapper.insertBillRecord(userAccountBill);
		
		UserFreezeFundAction userFreezeFundAction = new UserFreezeFundAction();
		userFreezeFundAction.setPlatform("WX");
		userFreezeFundAction.setUserId(currentUserId);
		userFreezeFundAction.setMoney(money);
		userFreezeFundAction.setStatus(FreezeFundState.CREATE);
		userFreezeFundAction.setType(FreezeFundActionType.PAY_BOND_MONEY);
		userFreezeFundAction.setDealNum(orderNum);
		String id = userAccountBill.getId();
		userFreezeFundAction.setBizId(id);
		saveUserFreezeFundAction(userFreezeFundAction);
		
		return orderNum;
	}

	@Override
	@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public Map<String, Object> applyFreezeFundStatus(String currentUserId) {
		String orderNum = orderNumGenerate.getDealNum(AccountBillBizType.MARGIN);
		//用户解冻审核中的保证金
		Long m = getUserFreezeFundStatus(currentUserId);
		if(m!=null ) error("解冻保证金正在审核");
		Long money = getUserFreezeFund(currentUserId);	
		if(money == null || money==0) error("未有可解冻的保证金");
		LogUtil.info(logger, "解冻保证金"+money/100+"元");
		
		//TODO 权限校验
		
		
		//插入账单记录表
		UserAccountBill userAccountBill = new UserAccountBill();
		userAccountBill.setUserId(currentUserId);
		userAccountBill.setDealNum(orderNum);
		userAccountBill.setMoney(money);
		userAccountBill.setName(NAME);
		userAccountBill.setStatus(FreezeFundState.AUDICTING);
		//userAccountBill.setType(AccountBillType.MARGIN);
		userAccountBill.setPlatform(PlatformEnum.PLATFORM_WX.getName());
		userAccountBill.setSubType(FreezeFundActionType.UNFREEZE_BOND_MONEY);
		userAccountBillMapper.insertBillRecord(userAccountBill);
		
		UserFreezeFundAction userFreezeFundAction = new UserFreezeFundAction();
		userFreezeFundAction.setPlatform(PlatformEnum.PLATFORM_WX.getName());
		userFreezeFundAction.setUserId(currentUserId);
		userFreezeFundAction.setMoney(money * (-1));
		userFreezeFundAction.setStatus(FreezeFundState.AUDICTING);
		userFreezeFundAction.setType(FreezeFundActionType.UNFREEZE_BOND_MONEY);
		userFreezeFundAction.setDealNum(orderNum);
		userFreezeFundAction.setBizId(userAccountBill.getId());
		saveUserFreezeFundAction(userFreezeFundAction);
		LogUtil.info(logger, "已提交，等待审核。。。。。。。");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("money", (userFreezeFundAction.getMoney()/100) * -1);
		//TODO 相关操作
		return map;
	}

	@Override
	@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public Map<String, Object> getFreezeFundStatus(String currentUserId) {
		String status = null;//保证金的状态 0：未缴纳 1：已缴纳 2：解冻审核中
		boolean isUnfreezeFund = false; 
		Map<String,Object> map = new HashMap<String,Object>();
		
		//用户的保证金
		Long moneys = getUserFreezeFund(currentUserId);
		//TODO 获取保证金的相关状态

		map.put("status", status);
		map.put("money", moneys / 100);
		map.put("isUnfreezeFund", isUnfreezeFund);
		return map;
	}

	/**
	 * 确认用户缴纳保证金接口
	 * @param 
	 * @author guohao
	 * @date 2016年2月23日 下午2:27:16
	 */
	@Override
	@Transactional(value=TransactionManagerType.FUND_TRANSACTION_MANAGER)
	public boolean confirmUserMargin(Long money, String orderNum, String payType) {
		synchronized (orderNum) {
			UserFreezeFundAction userFreezeFundAction = userFreezeFundActionMapper.loadFreezeFundByDealNum(orderNum);
	        if(userFreezeFundAction == null) {//
	        	
	        	LogUtil.info(logger, "需要确认的记录信息不存在");
	        	return false;
	        }
			if(userFreezeFundAction.getMoney().longValue() != money.longValue()) {
	        	//表示支付的金额和实际要收到的金额不同
	        	LogUtil.info(logger, "支付的金额不正确");
	        	return false;
	        }
			if(userFreezeFundAction.getStatus() == 10) {
				//表示已经成功确认支付了
				LogUtil.info(logger, "已经确认过");
				return false;
			}
			//执行确认功能
			userFreezeFundActionMapper.updateFreeFundActionStatus(userFreezeFundAction.getId(),10);
			userAccountBillMapper.updateUserAccountBillStatus(userFreezeFundAction.getBizId(),10);
			userFreezeFundActionMapper.updateFreezeFundPlatfrom(payType, userFreezeFundAction.getId());
			userAccountBillMapper.updateAccountBillPlatfrom(payType,userFreezeFundAction.getBizId());			
			
			//TODO 相关通知操作
			LogUtil.info(logger, "保证金缴纳确认成功");
		}		
		return true;
	}

}
